#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:taotieren


"""
    rpi.gpio 需要 root 权限，板上运行需要使用
    sudo python web_control_test.py
    使用 Web 接口控制 GPIO 输出
    可以通过 GitHub 下载这个对应的库代码
        sudo pip install bottle
    3 个 LED，3 个 1KΩ 电阻，1 个轻触开关
    Pin_18 ---- 1K------ LED_1 ----- GND
    Pin_23 ---- 1K------ LED_2 ----- GND
    Pin_24 ---- 1K------ LED_3 ----- GND
    Pin_25 -------------- KEY_Pin1
    GND ----------------- KEY_Pin2
    GND ---------------------------- GND
"""

from bottle import route, run

""" 非树莓派环境下可以用 rpi.gpio_def 代替 rpi.gpio 来进行程序调试和验证 """
import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BCM)
led_pins = [18, 23, 24]
led_states = [0, 0, 0]
switch_pin = 25

GPIO.setup(led_pins[0], GPIO.OUT)
GPIO.setup(led_pins[1], GPIO.OUT)
GPIO.setup(led_pins[2], GPIO.OUT)
GPIO.setup(switch_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)


def switch_status():
    state = GPIO.input(switch_pin)
    if state:
        return 'Up'
    else:
        return 'Down'


def html_for_led(led):
    i = str(led)
    result = "<input type = 'button' onClick = 'changed(" + i + ")'value = 'LED" + i + "'/>"
    return result


def update_leds():
    for i, value in enumerate(led_states):
        GPIO.output(led_pins[i], value)


@route('/')
@route('/<led>')
def index(led):
    if led >= '0' and led <= '9':
        led_num = int(led)
        led_states[led_num] = not led_states[led_num]
        update_leds()
    response = "<script>"
    response += "function changed(led)"
    response += "{"
    response += "  window.location.href='/' + led"
    response += "}"
    response += "</script>"

    response += '<h1>GPIO Control</h1>'
    response += '<h2>Button=' + switch_status() + '</h2>'
    response += '<h2>LEDs</h2>'
    response += html_for_led(0)
    response += html_for_led(1)
    response += html_for_led(2)
    return response


try:
    run(host='0.0.0.0', port=80)
finally:
    print('\nCleaning up')
    GPIO.cleanup()
